import os
import pika
from fastapi import FastAPI
import redis
import time
import json
import requests


def loadjson(jsonfile):
    with open(jsonfile) as json_file:
        data = json.load(json_file)
        return data


conf = loadjson(os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json"))
r = redis.Redis(host=conf['redis']['host'], port=conf['redis']['port'], db=0)
user_pwd = pika.PlainCredentials(conf['rabbitmq']['username'], conf['rabbitmq']['password'])
s_conn = pika.BlockingConnection(pika.ConnectionParameters(conf['rabbitmq']['host'], credentials=user_pwd, heartbeat=0))
chan = s_conn.channel()

app = FastAPI()


@app.get('/ls_queue')
def lsQueue():
    name = []
    response = requests.get(conf['rabbitmq']['http_api'] + "/api/queues",
                            auth=(conf['rabbitmq']['username'], conf['rabbitmq']['password']))
    res = json.loads(response.content)
    for line in res:
        if line['name']:
            name.append(line['name'])
    return name


@app.get('/add_queue')
def addQueue(q, job_text):
    now = time.strftime("%Y-%m-%d_%H_%M_%S")
    job = q + "_job_" + now
    data = {
        "body": job,
    }
    chan.queue_declare(queue=q, durable=True)
    chan.basic_publish(exchange='', routing_key=q,
                       body=json.dumps(data, ensure_ascii=False),
                       properties=pika.BasicProperties(delivery_mode=2))
    r.set(job, job_text)
    return {"ok"}


if __name__ == '__main__':
    import uvicorn

    runConf = conf['service']

    uvicorn.run(app=app,
                host=runConf['host'],
                port=runConf['port'],
                workers=runConf['workers'])
